package org.example.seckill.service;

import org.example.seckill.dao.ProductMapper;
import org.example.seckill.dao.pojo.Product;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class ProductService {

    @Autowired
    private ProductMapper productMapper;

    public void addInvenory(Product product, Integer step) {
        Product tProd = productMapper.findById(product.getId());
        step = step == null ? 1 : step;
        int prevInv = tProd.getInventory();
        System.out.println(">>>>------ prevInv: " + prevInv);
        product.setInventory(prevInv + step);
        productMapper.update(product);
    }

    public synchronized void deductInvenory(Product product, Integer step) {
        Product tProd = productMapper.findById(product.getId());
        step = step == null ? 1 : step;
        int prevInv = tProd.getInventory();
        System.out.println(">>>****-- prevInv for deductInventory: " + prevInv + " after: " + (prevInv - step));
        if ((prevInv - step) > -1) {
            product.setInventory(prevInv - step);
            System.out.println(">>>****++ product to persist: " + product.toString());
            productMapper.update(product);
        }
    }
}
